package com.jhscale.test.exception;

import com.codingapi.netflix.framework.Constants;
import com.ysscale.framework.exception.CommonException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lie_w
 * @title: GlobalExceptionHandler
 * @projectName public-address
 * @description: TODO
 * @date 2020/3/2713:38
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 返回的Map对象会被@ResponseBody注解转换为JSON数据返回
     *
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Object handleException(HttpServletRequest request, Exception e) {
        Map<String, Object> map = new HashMap<>();
        if (e instanceof CommonException) {
            map.put("code", ((CommonException) e).getCode());
            map.put("msg", ((CommonException) e).getMsg());
        } else {
            map.put("code", Constants.GLOBAL_EXCEPTION_DEFAULT_CODE);
            map.put("url", request.getRequestURL().toString());
            map.put("msg", e.getMessage());
        }
        return map;
    }
}
